<template>
    <div>
        <!--搜索栏-->
        <a-card class="card">
            <repository-form></repository-form>
        </a-card>
        <!--table-->
        <a-card class="card">
            <a-button type="primary" class="btnAdd" @click="addModalVisible = true">新增</a-button>
            <a-table 
                :columns="columns" 
                :data-source="data"
                :pagination="false">
                <template #sex="{record}">
                    <span v-if="record.sex === 'true'">男</span>
                    <span v-else>女</span>
                </template>
                <template #operation="{ record }">
                    <span>
                        <a @click="updateStudent(record.key)">编辑</a>
                        <a-divider type="vertical" />
                        
                        <a-popconfirm
                            title="是否确定删除?"
                            ok-text="确定"
                            cancel-text="取消"
                            @confirm="removeStudent(record.key)"
                            @cancel="cancelDelStudent"
                        >
                            <a>删除</a>
                        </a-popconfirm>

                        <a-divider type="vertical" />
                        <a class="ant-dropdown-link">
                            更多操作
                            <down-outlined />
                        </a>
                </span>
                </template>
            </a-table>
            <!--分页-->
            <a-row type="flex" class="components-pagination-demo-mini">
                <a-col flex="4" align="right"> 
                    <a-pagination 
                        v-model:current="current"
                        :page-size="pageSize"
                        size="small" 
                        :total="total" 
                        @change="onChange"
                        @showSizeChange="sizeChange"
                        :page-size-options="pageSizeOptions"
                        show-size-changer 
                        show-quick-jumper
                        :show-total="total => `当前第${current}页,共${total}条数据`" >
                        <template #buildOptionText="props">
                            <span v-if="props.value !== '50'">{{props.value}}条/页</span>
                            <span v-else>全部</span>
                        </template>
                    </a-pagination>
                </a-col>
            </a-row>
        </a-card>
        <!--添加弹出框-->
        <a-modal 
            v-model:visible="addModalVisible" 
            title="新增学生表信息" 
            width="50%"
            ok-text="新增"
            cancel-text="取消"
            @ok="addSubmit"
            @cancel="addModalCancel">
            <a-form
                ref="addFormRef"
                :model="addFormState"
                :rules="addFormStateRules"
                :label-col="labelCol" 
                :wrapper-col="wrapperCol">
                <a-row>
                    <a-col :span="12">
                        <a-form-item label="姓名" ref="name" required  name="name">
                            <a-input v-model:value="addFormState.name" placeholder="请输入姓名"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                         <a-form-item label="学号" required  name="studentId">
                            <a-input v-model:value="addFormState.studentId" placeholder="请输入学号"/>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col :span="12">
                        <a-form-item label="班级" required  name="className">
                            <a-input v-model:value="addFormState.className" placeholder="请输入班级"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                            <a-form-item label="性别" required  name="sex">
                                <a-select v-model:value="addFormState.sex" placeholder="please select your sex">
                                    <a-select-option value="true">男</a-select-option>
                                    <a-select-option value="false">女</a-select-option>
                                </a-select>
                            </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </a-modal>
        <!--编辑弹出框-->
        <a-modal 
            v-model:visible="editModalVisible" 
            title="编辑学生表信息" 
            width="50%"
            ok-text="保存"
            cancel-text="取消"
            @ok="editSubmit"
            @cancel="editModalCancel">
            <a-form
                ref="editFormRef"
                :model="editFormState"
                :rules="editFormStateRules"
                :label-col="labelCol" 
                :wrapper-col="wrapperCol">
                <a-row>
                    <a-col :span="12">
                        <a-form-item label="姓名" ref="name" required  name="name">
                            <a-input v-model:value="editFormState.name" placeholder="请输入姓名"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                         <a-form-item label="学号" required  name="studentId">
                            <a-input v-model:value="editFormState.studentId" placeholder="请输入学号"/>
                        </a-form-item>
                    </a-col>
                </a-row>
                <a-row>
                    <a-col :span="12">
                        <a-form-item label="班级" required  name="className">
                            <a-input v-model:value="editFormState.className" placeholder="请输入班级"/>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                            <a-form-item label="性别" required  name="sex">
                                <a-select v-model:value="editFormState.sex" placeholder="please select your sex">
                                    <a-select-option value="true">男</a-select-option>
                                    <a-select-option value="false">女</a-select-option>
                                </a-select>
                            </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </a-modal>
    </div>
</template>

<script>
import {defineComponent, reactive, toRefs,onMounted ,ref,provide} from 'vue';
import {Card,Table,Divider,Row,Col,Pagination,Modal,Message,Popconfirm,message } from 'ant-design-vue';
import {SmileOutlined, DownOutlined} from '@ant-design/icons-vue';
import { useForm } from '@ant-design-vue/use';
import axios from 'axios';
import RepositoryForm from './components/ResponsitoryForm.vue';

//定义表格表头
const columns = [
    {
        title:'姓名',
        dataIndex:'name',
        key:'name',
        width:'20%',
        slots:{ customRender:'name'}
    },{
        title:'学号',
        dataIndex:'studentId',
        key:'studentId',
        width:'20%',
        slots:{ customRender:'studentId'}
    },{
        title:'班级',
        dataIndex:'className',
        key:'className',
        width:'20%',
        slots:{ customRender:'className'}
    },{
        title:'性别',
        dataIndex:'sex',
        key:'sex',
        width:'15%',
        slots:{ customRender:'sex'}
    },{
        title:"操作",
        key:"action",
        slots:{ customRender: 'operation'}
    }
]
export default defineComponent({
    components: {
        RepositoryForm,
        SmileOutlined,
        DownOutlined
    },
    setup(){
        const addFormRef = ref(); 
        const editFormRef=ref();
        const state = reactive({
            current: 1 ,//显示当前第几页
            pageSize:10,//每页显示条数
            pageSizeOptions :['5','10', '20', '30', '40', '50'],
            data:[],//表格数据
            total:5000,//分页总数
            id: JSON.parse(sessionStorage.getItem("user_info")).id || '',
            addModalVisible: false,//控制添加弹出框的显示与隐藏
            labelCol:{span:6}, //控制表单
            wrapperCol:{span:16},
            editModalVisible:false ,//控制编辑弹出框的显示与隐藏
            editFormState:{}
        })
        //add form数据
        const addFormState = reactive({
           name:'',
           studentId:'',
           className:'',
           sex:''
        })
        

        //添加表单 数据校验
        const addFormStateRules = {  
          name: [{ required: true, message: '请输入学生名字', whitespace: true}],
          studentId: [{ required: true, message: '请输入学生学号', whitespace: true}],
          className: [{ required: true, message: '请输入学生班级', whitespace: true}],
          sex: [{ required: true, message: '请选择学生性别'}],
        }

        const editFormStateRules = {  
          name: [{ required: true, message: '请输入学生名字', whitespace: true}],
          studentId: [{ required: true, message: '请输入学生学号', whitespace: true}],
          className: [{ required: true, message: '请输入学生班级', whitespace: true}],
          sex: [{ required: true, message: '请选择学生性别'}],
        }

        //const {resetFields,validate,validateInfos} = useForm(addFormState,addFormStateRules);

        const getStudentList =async () => {
            const res = await axios.get('/api/students/getStudentList',{params:{
                current:state.current,
                pageSize:state.pageSize
            }});
            console.log(res);
            state.data = res.data.data;
            state.total = res.data.total;
            console.log(state.total);
        }

        const onChange = (pageNumber) => {
            console.log("onChange",pageNumber);
            state.current = pageNumber;
            getStudentList();
        }
        
        const sizeChange = (current,size)=>{
            console.log("sizeChange",size);
            state.pageSize = size;
            getStudentList();
        }

        onMounted(()=>{
            console.log("onMounted",state.id);
            getStudentList();
        })

        const addModalCancel = ()=>{
        
            //重置表单
            addFormRef.value.resetFields();
            state.addModalVisible = false;
        }
        const addSubmit = ()=>{
             addFormRef.value.validate().then(async ()=>{
                 console.log("addSubmit 添加成功");
                 const res = await axios.post("/api/students/saveStudent",addFormState);
                 console.log("res",res);
                 if(res.data.status === 200){
                    getStudentList();
                    message.success(res.data.message);
                    state.addModalVisible = false;
                 }
             }).catch(err => {
                 console.log("数据校验",err);
             })
             
        }
        //删除功能
        const removeStudent = async (key) => {
            // console.log(key);
           const res = await axios.get('/api/students/removeStudent',{params:{key:key}})
           console.log("removeStudent",res);
           if(res.data.status === 200){
               getStudentList();
               message.success(res.data.message);
           }

        }
        const cancelDelStudent = ()=>{
            message.error("删除失败");
        }
        //更新操作
        const updateStudent =async (key) => {
            const {data:res} = await axios.get("/api/students/getStudentByKey",{params:{key:key}})
            console.log("updateStudent",res);
            if(res.status === 200){
                state.editFormState = res.data;
                console.log("editFormState",state.editFormState);
                state.editModalVisible = true;
            }
        }
        const editSubmit = ()=>{
             editFormRef.value.validate().then(async ()=>{
                 console.log("editSubmit 更新成功");
                 const res = await axios.post("/api/students/updateStudent",state.editFormState);
                 console.log("res",res);
                 if(res.data.status === 200){
                    getStudentList();
                    message.success(res.data.message);
                    state.editModalVisible = false;
                 }
             }).catch(err => {
                 console.log("数据校验",err);
             })
             
        }
        const editModalCancel = ()=>{
            //重置表单
            addFormRef.value.resetFields();
            state.addModalVisible = false;
        }

        //父子组件交互
        const changeStudentList = (n,m) => {
            console.log("n",n);
            state.data = n;
            state.total = m;
        }

        provide('changeStudentList',changeStudentList);

        return {
            ...toRefs(state),
            addFormState, //添加表单数据
            columns, //表格表头
            getStudentList,//获取学生列表
            addFormStateRules,//添加表单数据校验规则
            addSubmit,//对话框添加事件
            addModalCancel,//对话框取消事件
            addFormRef, //添加表单
            removeStudent, //删除操作
            cancelDelStudent ,//取消删除操作
            updateStudent, //更新操作
            editFormStateRules,//编辑表单数据校验规则
            editFormRef, //编辑表单
            editSubmit,//更新操作
            editModalCancel,//对话框取消事件
            onChange,
            sizeChange
        }
    }
})
</script>

<style lang="less" scoped>
.card{
     margin:0px 16px 24px 16px;
}
.btnAdd{
    margin-bottom: 10px;
}
.components-pagination-demo-mini{
     margin-top: 20px;
    
}
</style>